<?php

namespace App\Http\Controllers;

use App\Http\Model\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

require_once  'resources/org/code/Code.class.php';//引入验证码扩展包

class LoginController extends Controller//登录控制器
{
    public function login(){//登录方法
        if( $input = Input::all() ){//判断是否有输出传输过来
            $code = new \Code();//实例化验证码类
            $_code = $code->get();

            if( strtoupper( $input['code'] ) != $_code ){//判断验证码对否
                return back()->with('msg','验证码错误');
            }

            $admin = Admin::where('account','=',$input['account'])->first();//查询admin数据表中是否有这个账号
            if($admin){
                $account = $admin->account;
                $password = $admin->password;
            }else{
                return back()->with( 'msg','账号不存在' );
            }

            if( $account != $input['account'] || Crypt::decrypt( $password ) != $input['password'] ){//判断密码是否正确
                return back()->with( 'msg','账号或者密码错误' );
            }
            if(!$admin->state){//判断账号是否被禁
                return back()->with( 'msg','账号被禁用！' );
            }
            DB::table('admin')->where('account','=',$input['account'])->update(['lasttime'=>time()]);//更新表中最后一次登录时间
            session( ['admin' => $admin] );//把账号信息存进缓存session中
            return redirect( 'index' );
        }else{
            return view( 'home.login' );
        }

    }

    public function quit(){//退出方法
        session(['admin'=>null]);//清除缓存session数据
        return redirect( 'login' );
    }

    public function code(){//获取验证码方法
        $code = new \Code;
        $code->make();
    }

}
